import urllib2, cookielib, re

global domain
global browser

domain="http://www.animenewsnetwork.com"
cj=cookielib.CookieJar()
cj.clear()
CHandler = urllib2.HTTPCookieProcessor(cj)
browser = urllib2.build_opener(CHandler)
browser.addheaders = [('User-agent', 'Mozilla/5.0')]
urllib2.install_opener(browser)

def get_tag(query, tag_type=0):
	global browser
	global domain
	link=0
	tag_types=["anime","manga","person","company","lexicon"]
	req=req=urllib2.Request(domain+"/encyclopedia/search/name?q="+query)
	res=browser.open(req)
	results=re.findall('results for(.*?)</div>',res.read(),re.DOTALL)
	results=results[0].split("<br />")
	for result in results:
		last= re.findall('\s\s\s(.*?)\s<a\shref="(.*?)">(.*?)</a>',result)
		if len(last)>0 and tag_types[0]==last[0][0]:
			link=last[0][1]
			break
	if not link==0:
		req=req=urllib2.Request(domain+link)
		res=browser.open(req)
		results=re.findall('<title>(.*?)\s-\sAnime\sNews\sNetwork</title>',res.read(),re.DOTALL)
		results.append(link.split("=")[1])
		return results
	else:
		return None
